using System;
using System.Configuration;
using System.IO;
using System.Text;
using TripleA.Core.Extensions.Process;
using TripleA.Core.Interfaces.Entities;

namespace TripleA.Core.Extensions.Database
{
    public class SqlServer2008RunScript<T> : RunProcessStep<T> where T : Context
    {
        public const int OneDay = 86400000;

        public string ScriptFilename { get; set; }
        public string Server { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string OtherArgs { get; set; }

        public override void Execute(T context)
        {
            if (string.IsNullOrWhiteSpace(ExeFilePath))
            {
                ExeFilePath = ConfigurationManager.AppSettings["SqlCmdPath"];

                if (string.IsNullOrWhiteSpace(ExeFilePath))
                {
                    var msg = new StringBuilder();
                    msg.AppendLine("sqlcmdPath (ExeFilePath) parameter was not supplied or null/empty.");
                    msg.AppendLine("You can set a default for this by creating an appSetting named 'SqlCmdPath' that contains the full path to sqlcmd.exe");
                    throw new ApplicationException(msg.ToString());
                }

                if (!File.Exists(ExeFilePath))
                {
                    
                }
            }

            var argsBuilder = new StringBuilder();

            argsBuilder.Append("-b")
                .AppendFormatNotNullOrWhitespace(" -S {0}", Server)
                .AppendFormatNotNullOrWhitespace(" -i {0}", ScriptFilename)
                .AppendFormatNotNullOrWhitespace(" -U {0} -P {1}", Username, Password)
                .AppendFormatNotNullOrWhitespace(" {0}", OtherArgs);

            WaitForExit = OneDay;
            ExitCode = 0;
            Args = argsBuilder.ToString();
            base.Execute(context);
        }
    }
}